package com.empresa.iflex.core;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.empresa.iflex.R;
import com.empresa.iflex.database.IFlexDbAdapter;

public class Mes extends ListActivity {
	
	private IFlexDbAdapter ida;
	private SQLiteDatabase db;
	Cursor c;
	

	/* Chamada quando o programa eh inicializado */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.historico);
      
        this.ida = new IFlexDbAdapter(getApplicationContext());
		this.db = ida.open();
        
		povoaLista();
    }
    
    public void povoaLista(){
		c = Percurso.groupByMonth(db); 
        startManagingCursor(c);

        // mes_ano | total_km | t_gasolina | m_gasolina | t_etanol | m_etanol
    	String[] colunas = new String[]{"mes_ano", "total_km", "t_gasolina", "m_gasolina", "t_etanol", "m_etanol"};
    	int[] to = new int[]{R.id.mes_ano, R.id.total_km, R.id.t_gasolina, R.id.m_gasolina, R.id.t_etanol, R.id.m_etanol};
    	
    	ListAdapter la = new SimpleCursorAdapter(getApplicationContext(), R.layout.col_mes, c, colunas, to);
    	
    	setListAdapter(la);
    }
    
    @Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
    	Cursor cursor = (Cursor) l.getItemAtPosition(position);
    	
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);  
    	builder.setIcon(R.drawable.f);
    	builder.setTitle(cursor.getString(cursor.getColumnIndex("mes_ano")));
	    builder.setMessage("Total percorrido no mês: \n\t" + cursor.getString(cursor.getColumnIndex("total_km")) + " Km"
        		+ "\n---\nTotal gasto com gasolina: \n\tR$ " + cursor.getString(cursor.getColumnIndex("t_gasolina"))
        		+ "\n\nCusto médio da gasolina: \n\tR$ " + cursor.getString(cursor.getColumnIndex("m_gasolina")) + " /Litro"
        		+ "\n--\nTotal gasto com etanol: \n\tR$ " + cursor.getString(cursor.getColumnIndex("t_etanol"))
        		+ "\n\nCusto médio do etanol: \n\tR$ " + cursor.getString(cursor.getColumnIndex("m_etanol")) + " /Litro")
        		.setCancelable(false)
        		.setPositiveButton("Ok", new DialogInterface.OnClickListener(){ 
        			public void onClick(DialogInterface dialog, int id){  
        				dialog.cancel();
	    	    }  
	    }); 
    	AlertDialog alert = builder.create();  
    	alert.show();
		super.onListItemClick(l, v, position, id);
	}

	@Override
    public void onResume(){
    	super.onResume();
    	
    	povoaLista();
    }
    
    @Override
    public void onDestroy() {
    	super.onDestroy();
    	if (db != null){
    		db.close();
    		ida.close();
    	}
    }
	
}
